import { onMounted , ref } from "vue";
import { useLoginStore } from "@/stores/loginStore"
import type { User } from "@/interface/User"
import { getAreaInfoApi , getWeatherInfoApi } from "@/controller/GaoDeApi";
import type {GaoDe} from "@/interface/GaoDe";

export default function () {

    const loginStore = useLoginStore();


    let user = ref({} as User);

    onMounted(()=> {
       setUser();
       getLocation();
    });

    const position = ref<GaoDe>( {
        latitude: 0,
        longitude: 0
    });

    let weatherInfo = ref({} as any);
    function getLocation() {
        try {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition( (location : GeolocationPosition ) => {
                    position.value.latitude = location.coords.latitude;
                    position.value.longitude = location.coords.longitude;
                    getAreaInfoApi(position.value).then( res  => {
                        if (res.code === 200) {
                            getWeatherInfoApi({ adCode : res.data.addressComponent.adcode }).then( res => {
                                if (res.code === 200) {
                                    weatherInfo.value = res.data[0];
                                }
                            });
                        }
                    });
                });
            }
        } catch (error) {
            console.log(error);
        }
    }

    function setUser() {
        if (loginStore.loginInfo.user) {
            let loginUerDto=  loginStore.loginInfo.user;
            user.value = loginUerDto.user;
        }
    }

    function reload() {
        location.reload()
    }

    function loginOut() {
        loginStore.loginOut();
    }

    return {
        reload , user , loginOut , weatherInfo
    }
}
